﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using HtmlAgilityPack;
using MusicExplorer.Data;
using MusicExplorer.WebRepository.Interface;
using MusicExplorer.WebRepository.Service;

namespace MusicExplorer.WebRepository
{
    public class WorldofhouseWebRepository : WebRepositoryBase,
        IGroupFilterWebRepository
    {
        private const string m_url_GENRES = "http://www.worldofhouse.es/";

        public WorldofhouseWebRepository()
        {
            m_web_repository = ServiceWebRepository.GetWebRepository(ServiceWebRepository.GetTypeWebRepository(TypeWebRepository.WebsiteDatabase), this.GetType().Name);
            m_result_per_page = 10;
        }

        public async Task<List<GROUP>> GetGroupsAsync(WebClient webClient, CancellationToken token)
        {
            List<GROUP> genres = new List<GROUP>();
            HtmlDocument doc = new HtmlDocument();
            token.ThrowIfCancellationRequested();
            doc.LoadHtml(await ServiceWebRepository.GetUrlDataAsync(webClient, m_url_GENRES));
            token.ThrowIfCancellationRequested();
            var genre_sub_header = doc.GetElementbyId("sub_header");
            var mul_genres_node = genre_sub_header.ChildNodes.Where(child => child.Attributes != null && child.Attributes.Contains("class") && child.Attributes["class"].Value == "genre_menu_list");
            foreach (var genre_node in mul_genres_node.SelectMany(n => n.ChildNodes.Where(c => c.Name == "a")))
            {
                var div_node = genre_node.ChildNodes["div"].ChildNodes["div"];
                
                var group = new GROUP()
                {
                    group_key = genre_node.Attributes["href"].Value.Split('/')[1],
                    group_name = div_node.InnerText,
                    web_repo_id = m_web_repository.web_repo_id
                };

                group = ServiceWebRepository.InsertOrUpdateGroup(group);

                genres.Add(group);

                token.ThrowIfCancellationRequested();
            }

            return genres;
        }
    }
}
